package net.vkits.common.push.umeng;

import com.alibaba.fastjson.JSON;
import net.vkits.common.push.PushService;
import net.vkits.common.push.umeng.android.AndroidBodyEntity;
import net.vkits.common.push.umeng.android.PayloadEntity;
import net.vkits.common.push.umeng.android.UmengAndroidMsg;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by ethan-liu on 2016/11/22.
 */
public class UmengPushService implements PushService {

    private static final Logger logger = LoggerFactory.getLogger(UmengPushService.class);

    // The host
    private static final String url = "http://msg.umeng.com/api/send";
    // The user agent
    private final String USER_AGENT = "Mozilla/5.0";
    // The app master secret
    private String appMasterSecret = "5bklwmvw5alwb6hzgaqcmg3jdfac9m6a";
    // The app key
    private String appKey = "587c4c11734be435f60004a1";
    //HttpClient
    private CloseableHttpClient client  = HttpClientBuilder.create().build();

    @Override
    public boolean push2Unique4Android(String deviceToken, String ticker, String title, String text) {
        AndroidBodyEntity bodyEntity = new AndroidBodyEntity
                .Builder(ticker, title, text, AndroidBodyEntity.AfterOpenAction.go_app)
                .createAndroidBodyEntity();
        PayloadEntity payloadEntity = new PayloadEntity(DisplayType.notification, bodyEntity, null);
        UmengAndroidMsg msg = new UmengAndroidMsg(payloadEntity);
//        AndroidPolicy policy = new AndroidPolicy();
//        msg.setPolicy(policy);
        msg.setDevice_tokens(deviceToken);
        msg.setType(MessageSendType.unicast);
        msg.setAppkey(appKey);
        return this.send(msg);
    }

    @Override
    public boolean push2List4Android(String deviceTokens, String ticker, String title, String text) {
        AndroidBodyEntity bodyEntity = new AndroidBodyEntity
                .Builder(ticker, title, text, AndroidBodyEntity.AfterOpenAction.go_app)
                .createAndroidBodyEntity();
        PayloadEntity payloadEntity = new PayloadEntity(DisplayType.notification, bodyEntity, null);
        UmengAndroidMsg msg = new UmengAndroidMsg(payloadEntity);
//        AndroidPolicy policy = new AndroidPolicy();
//        msg.setPolicy(policy);
        msg.setDevice_tokens(deviceTokens);
        msg.setType(MessageSendType.listcast);
        msg.setAppkey(appKey);
        return this.send(msg);
    }

    @Override
    public boolean pushCustom2Android(String deviceTokens, String ticker, String title, String text, String custom) {
        AndroidBodyEntity bodyEntity = new AndroidBodyEntity
                .Builder(ticker, title, text, AndroidBodyEntity.AfterOpenAction.go_custom)
                .custom(custom)
                .createAndroidBodyEntity();
        PayloadEntity payloadEntity = new PayloadEntity(DisplayType.notification, bodyEntity, null);
        UmengAndroidMsg msg = new UmengAndroidMsg(payloadEntity);
//        AndroidPolicy policy = new AndroidPolicy();
//        msg.setPolicy(policy);
        msg.setDevice_tokens(deviceTokens);
        msg.setType(MessageSendType.listcast);
        msg.setAppkey(appKey);
        return this.send(msg);
    }

    private boolean send(UmengAndroidMsg msg) {
        try {
            String content = JSON.toJSONString(msg);
            String sign = DigestUtils.md5Hex(("POST" + this.url + content + this.appMasterSecret).getBytes("utf8"));
            String signUrl = this.url + "?sign=" + sign;
            HttpPost post = new HttpPost(signUrl);
            post.setHeader("User-Agent", this.USER_AGENT);
            StringEntity se = new StringEntity(content, "UTF-8");
            post.setEntity(se);
            HttpResponse response = this.client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            System.out.println("Response Code : " + status);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line;
            while((line = rd.readLine()) != null) {
                result.append(line);
            }
            System.out.println(result.toString());
            if(status == 200) {
                logger.debug("Notification sent successfully.");
                return true;
            } else {
                logger.debug("Failed to send the notification!");
                return false;
            }
        } catch (IOException e) {
            logger.error("Error: ", e);
        }
        return false;
    }
}
